const os = require('os')
const portfinder = require('portfinder')

const checker = require('./checker')
const { info } = require('./output')

// 获取本机 IPv4 地址
const getIPv4Address = () => {
  const interface = os.networkInterfaces()
  for (const key in interface) {
    for (const { family, address, internal } of interface[key]) {
      if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
        return address
      }
    }
  }
}

// 获取可用的端口号
const getPort = async () => {
  portfinder.basePort = 3000
  const port = await portfinder.getPortPromise()
  return port
}

// 获取完整的IP地址 IPv4+端口 导出完整地址和端口
const getValidIPAddress = async () => {
  info('获取IPv4地址...')
  const IPv4Address = getIPv4Address()
  const port = await getPort()
  checker(IPv4Address, '获取成功', '无法获取IPv4地址，请检查你的网络连接')
  const IPAddress = IPv4Address + ':' + port
  return { IPAddress, port }
}

module.exports = getValidIPAddress